<!--
 * @Author: tenet 18742176629@163.com
 * @Date: 2024/6/25 下午4:50
 * @LastEditors: tenet 18742176629@163.com
 * @LastEditTime: 2024/6/25 下午4:50
 * @FilePath: G:/block-watch-sys/src/views/user\index.vue
 * @Description: 用户管理
-->
<template>

  <el-form :model="queryObj" :inline="true" class="query-form">
    <el-form-item label="用户名">
      <el-input v-model="queryObj.username" placeholder="请输入用户名"></el-input>
    </el-form-item>
    <el-form-item label="邮箱地址">
      <el-input v-model="queryObj.email" placeholder="请输入邮箱地址"></el-input>
    </el-form-item>
    <el-form-item label="状态">
      <el-select v-model="queryObj.status" placeholder="请选择状态" clearable style="width: 200px;">
        <el-option label="启用" value="1" />
        <el-option label="禁用" value="0" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getList">
        查询
      </el-button>
      <el-button type="default" @click="resetQuery">
        重置
      </el-button>
    </el-form-item>
  </el-form>

  <!-- 查询 -->
  <div class="queryBar">
    <!--    <query-bar :title="$t('title.UserManagement')">-->
    <!--      &lt;!&ndash;    查询按钮&ndash;&gt;-->
    <!--      <el-form :inline="true" :model="queryParams" class="demo-form-inline">-->
    <!--        <el-form-item :label="$t('user.UserName')" style="width: 250px; margin-bottom:0; margin-right: 20px">-->
    <!--          <el-input v-model.trim="queryParams.username" :placeholder="$t('global.PleaseInput') + $t('user.UserName')"-->
    <!--                    clearable/>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item :label="$t('user.UserStatus')" style="width: 250px; margin-bottom: 0; margin-right: 20px">-->
    <!--          <el-select v-model.trim="queryParams.status"-->
    <!--                     :placeholder="$t('global.PleaseSelect') + $t('user.UserStatus')" clearable>-->
    <!--            <el-option v-for="(item, index) in userStatusList" :key="index" :label="item.label" :value="item.value"/>-->
    <!--          </el-select>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item style="margin-bottom: 0">-->
    <!--          <el-button type="primary" :icon="Search" @click="onSubmit(queryParams.username, queryParams.status)">{{$t('button.Search') }}</el-button>-->
    <!--          <el-button type="default" :icon="Refresh" plain @click="onReset()">{{ $t('button.Reset') }}</el-button>-->
    <!--        </el-form-item>-->
    <!--      </el-form>-->
    <!--    </query-bar>-->
    <div class="query_btns">
      <el-row :gutter="8">
        <el-col :span="1.5">
          <el-button type="primary" plain size="small" :icon="Plus" @click="handleCLick(scope, 'add')">
            {{ $t('button.Add') }}
          </el-button>
        </el-col>
      </el-row>
    </div>
  </div>

  <el-table :data="tableData" border ref="multipleTableRef" style="width: 100%;" size="large" v-loading="loading"
    max-height="600px">
    <el-table-column prop="id" :label="$t('user.UserId')" width="" align="center" />
    <el-table-column prop="username" :label="$t('user.UserName')" width="" align="center" />
    <el-table-column prop="email" :label="$t('table.Email')" width="" align="center" />
    <el-table-column prop="status" :label="$t('user.UserStatus')" width="" align="center">
      <template #default="scope">
        <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" class="ml-2" active-color="#13ce66"
          inactive-color="#ff4949" @change="handleSwitchChange(val, scope)" />
      </template>
    </el-table-column>
    <el-table-column prop="maturityTime" :label="$t('table.MaturityTime')" width="auto" align="center">
      <template #default="scope">
        {{ formatTimestamp(scope.row.maturityTime) }}
      </template>
    </el-table-column>
    <el-table-column prop="remark" :label="$t('table.Remark')" width="auto" align="center" />
    <el-table-column fixed="right" :label="$t('global.Operation')" width="150" align="center">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="handleCLick(scope, 'edit')">{{
          $t('button.Edit')
        }}
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="page">
    <el-pagination v-model:current-page="pageIndex" :page-size="pageSize" layout="total, prev, pager, next"
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>

  <!--  新增 和 修改用户时的dialog-->
  <el-dialog :title="dialogTitleText" v-model="dialogVisible" width="500" @closed="handleClose" center>
    <!-- 表单内容将在这里 -->
    <div v-if="dialogTitle === 'add' || dialogTitle === 'edit'"
      style="width: 100%; display: flex;flex-direction: row; justify-content: center; align-items: center">
      <el-form :model="ruleForm" label-width="auto" :rules="rules" ref="ruleRef" label-position="right"
        style="max-width: 500px; " center>
        <el-form-item v-if="dialogTitle === 'edit'" :label="$t('dialog.UserId')" prop="userId" style="width: 100%">
          <el-input disabled v-model.trim="ruleForm.userId"
            :placeholder="$t('global.PleaseInput') + $t('dialog.UserId')" style="border-radius: 30px; width: 100% " />
        </el-form-item>
        <el-form-item :label="$t('dialog.UserName')" prop="userName" style="width: 100%">
          <el-input v-model.trim="ruleForm.userName" :placeholder="$t('global.PleaseInput') + $t('dialog.UserName')"
            style="border-radius: 30px; width: 100%;" />
        </el-form-item>
        <el-form-item :label="$t('dialog.Password')" prop="password">
          <el-input :type="inpType" v-model.trim="ruleForm.password"
            :placeholder="$t('global.PleaseInput') + $t('table.Password')" style="width: 100%">
            <template #suffix>
              <svg class="icon eyeopen" aria-hidden="true" @click="checkPass" v-show="!eye">
                <use xlink:href="#icon-eye-lined"></use>
              </svg>
              <svg class="icon eyeclose" aria-hidden="true" @click="checkPass" v-show="eye">
                <use xlink:href="#icon-eye-close-lined"></use>
              </svg>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('dialog.Email')" prop="email">
          <el-input type="text" v-model.trim="ruleForm.email"
            :placeholder="$t('global.PleaseInput') + $t('table.Email')" style="width: 100%" />
        </el-form-item>
        <el-form-item :label="$t('table.Remark')" prop="remark" style="width: 100%">
          <el-input v-model.trim="ruleForm.remark" :placeholder="$t('global.PleaseInput') + $t('table.Remark')"
            style="border-radius: 30px; width: 100%;" />
        </el-form-item>
        <el-form-item :label="$t('table.MaturityTime')">
          <el-date-picker v-model="ruleForm.maturityTime" :disabled-date="disabledDate"
            :placeholder="$t('global.PleaseSelect') + $t('table.MaturityTime')" type="datetime"
            format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :clearable="false" />
        </el-form-item>
        <el-form-item :label="$t('global.emailCode')" style="width: 100%" v-if="dialogTitle === 'edit'">
          <el-input style="width: 100px;" v-model="ruleForm.code"></el-input>
          <el-button style="width: 150px;" @click="getEmailCode" :disabled="isThrottled">
            <span v-show="!isThrottled">
              {{ $t('global.GetCode') }}
            </span>
            <span v-show="isThrottled">
              {{ `${remainingTime}${$t('global.reSendCode')}` }}
            </span>
          </el-button>
        </el-form-item>
        <!-- 其他表单项... -->
      </el-form>
    </div>

    <!-- 对话框底部按钮 -->
    <span slot="footer" class="dialog-footer" style="margin-left: 0; display: flex;justify-content: flex-end">
      <el-button @click="handleClose"> {{ $t('global.Cancel') }} </el-button>
      <el-button type="primary" @click="handleConfirm">{{ $t('global.Submit') }}</el-button>
    </span>
  </el-dialog>

  <!--  冻结用户时的dialog-->
  <el-dialog :title="t('dialog.systemTip')" v-model="freezeDialog" width="30%" @closed="handleCloseFreeze">
    <!--
        0 提示要禁用吗
        1 提示要启用吗
    -->
    <div v-if="userStatus === 0" style="margin: .1rem 0 .2rem 0">
      {{ t('dialog.ToConfirm') }}
      <span style="color: red">{{ t('dialog.Freeze') }}</span>
      <span>{{ rowUserName }}</span>
      <span>{{ t('dialog.Account') }}</span>
    </div>
    <div v-else-if="userStatus === 1" style="margin: .1rem 0 .2rem 0">
      {{ t('dialog.ToConfirm') }}
      <span style="color: #3967FF">{{ t('dialog.Enable') }}</span>
      <span>{{ rowUserName }}</span>
      <span>{{ t('dialog.Account') }}</span>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="handleCloseUserStatus"> {{ $t('global.Cancel') }} </el-button>
      <el-button type="primary" @click="handleConfirmUserStatus">{{ $t('global.Submit') }}</el-button>
    </span>
  </el-dialog>

</template>

<script setup>
import { ref, onMounted, unref, reactive, watch, watchEffect, computed } from 'vue'
import { Delete, Edit, Plus, Refresh, Search, Upload, ArrowDown, ArrowUp } from "@element-plus/icons-vue";
import { useUserStore } from "@/stores";
import { formatTimestamp } from "@/utils/timeStamp";
import queryBar from "@/components/queryBar/index.vue"
import { ElMessage, ElPagination, ElTable, ElSwitch } from "element-plus";
import { getUserList, changeStatus, createUser, updateUser, getEmailCodeApi } from "@/require/api.js"
import { useI18n } from "vue-i18n";

const { t } = useI18n();

// 在组件被挂载后执行
onMounted(() => {
  getList();
  // 初始化时也可以设置一次
  if (dialogTitle.value === 'add') {
    dialogTitleText.value = t('dialog.UserAdd');
  } else if (dialogTitle.value === 'edit') {
    dialogTitleText.value = t('dialog.UserEdit');
  } else {
    dialogTitleText.value = ''
  }
});



const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7;
}

const queryObj = ref({
  username: "",
  email: "",
  status: "",
});

const pageSize = ref(10)
const pageIndex = ref(1)
const total = ref(0)
const tableData = ref([])
const loading = ref(false)
const ruleRef = ref(null);
const userStore = useUserStore();

const originPWD = ref('') // 原来的密码

const dialogVisible = ref(false) // 修改用户信息表单
const freezeDialog = ref(false) // 禁用用户tips
const dialogTitle = ref('')
const dialogTitleText = ref('')
// const switchState = ref(tableData.value.status) // 用户状态开关, 根据状态值来设置初始状态
const userStatus = ref('') // 用户状态 用户状态 0:您要启用该用户吗？ 1:您要禁用该用户吗

// 获取用户列表
async function getList() {
  try {
    loading.value = true
    const { code, data, msg } = await getUserList({
      pageSize: unref(pageSize),
      pageIndex: pageIndex.value,
      username: queryObj.value.username || null,
      email: queryObj.value.email || null,
      status: queryObj.value.status || null,
    })
    if (code === 200) {
      tableData.value = data.list
      total.value = data.total
    } else {
      ElMessage.error(msg)
    }

  } catch (e) {
    console.log(e)
  } finally {

    loading.value = false
  }
}

function resetQuery() {
  queryObj.value.username = "";
  queryObj.value.email = "";
  queryObj.value.status = "";
  getList();
};

// 查询参数
const queryParams = reactive([
  {
    id: '',
    username: '',
    email: '',
    maturityTime: '',
    status: '',
    time: [],
    startTime: '',
    endTime: ''
  }
])

// 表单数据
const ruleForm = reactive({
  userName: '',
  userId: '',
  status: '',
  password: '',
  email: '',
  code: '',
  maturityTime: '',
  remark: '',
  // hasPasswordChanged: false, // 新添加的属性
})


// 新增 和 更新用户 表单提交方法
async function handleConfirm() {
  // ruleForm.startTime = ruleForm.time ? ruleForm.time[0].getTime() / 1000 : '';
  // ruleForm.endTime = ruleForm.time ? ruleForm.time[1].getTime() / 1000  : '';

  try {
    // 如果选择的日期在当前时间之前,那么给出提示
    if (ruleForm.maturityTime) {
      if (ruleForm.maturityTime.getTime() / 1000 < new Date().getTime() / 1000 - 1000) {
        ElMessage.error(t('message.PastTime'))
        return
      }
    }

    if (dialogTitle.value === 'add') {
      ruleRef.value.validate(async (valid) => {
        if (!valid) {
          ElMessage.error(t("message.CheckInput"));
          return false;
        }
        // 新增逻辑
        if (!ruleForm.userName || !ruleForm.password || !ruleForm.email) {
          ElMessage.error(t('message.InputAll'))
        }

        const { code, data, msg } = await createUser({
          userName: ruleForm.userName,
          password: ruleForm.password,
          email: ruleForm.email,
          maturityTime: ruleForm.maturityTime ? ruleForm.maturityTime.getTime() / 1000 : 0,
          remark: ruleForm.remark
        })
        if (code === 200) {
          ElMessage.success(t('message.AddSuccess'))
          handleClose(); // 关闭 dialog
        } else {
          ElMessage.error(msg)
        }
      })

    } else if (dialogTitle.value === 'edit') {
      if (!ruleForm.userId || !ruleForm.userName || !ruleForm.password || !ruleForm.email) {
        ElMessage.error(t('message.InputAll'))
      }

      // 检查密码是否已更改
      // if (!ruleForm.hasPasswordChanged && ruleForm.password === originPWD.value) {
      //   // 密码未更改，跳过密码规则校验
      //   ruleForm.password = ''; // 可以选择性地清空密码字段，或者保留其原始值
      // }
      // 更新逻辑

      const { code, data, msg } = await updateUser({
        id: ruleForm.userId,
        userName: ruleForm.userName,
        password: originPWD.value === ruleForm.password ? '' : ruleForm.password,
        email: ruleForm.email,
        code: ruleForm.code,
        maturityTime: ruleForm.maturityTime ? ruleForm.maturityTime.getTime() / 1000 : 0,
        remark: ruleForm.remark
      })
      if (code === 200) {
        ElMessage.success(t('message.EditSuccess'))
        handleClose(); // 关闭 dialog
      } else {
        ElMessage.error(msg)
      }



    } else if (dialogTitle.value === 'delete') {
      // 删除确认逻辑，通常会有一个二次确认
    }

  } catch (e) {
    console.log(e)
  } finally {
    await getList();
  }
}

// 监听 dialogTitle 的变化
watch(dialogTitle, (newValue) => {
  // 如果既不是 'add' 也不是 'edit'，则清空文本
  dialogTitleText.value = newValue === 'add' ? t('dialog.UserAdd') : newValue === 'edit' ? t('dialog.UserEdit') : '';
});


// 使用watchEffect监听tableData.status的变化
// watchEffect(() => {
//   userStatus.value = tableData.value.status;
// });

// 点击按钮方法
const handleCLick = (scope, v) => {
  dialogVisible.value = true;
  dialogTitle.value = v
  // dialogTitleText.value = dialogTitle.value === 'add' ? t('dialog.UserAdd') : t('dialog.UserEdit')
  if (v === 'add') {
    // 调用添加方法
  } else if (v === 'edit') {
    ruleForm.userId = scope.row.id
    ruleForm.userName = scope.row.username
    ruleForm.password = scope.row.password
    originPWD.value = scope.row.password
    ruleForm.email = scope.row.email
    ruleForm.maturityTime = scope.row.maturityTime ? new Date(scope.row.maturityTime * 1000) : ''
    ruleForm.remark = scope.row.remark
    // 调用编辑方法
  } else if (v === 'del') {
    // 调用删除方法
  }
}

// 是否处于节流状态
const isThrottled = ref(false);
// 发送验证码剩余时间
let remainingTime = ref(60);

// 节流函数
function throttle(fn) {
  // 如果处于节流状态，直接返回
  if (isThrottled.value) return;
  isThrottled.value = true;
  fn();
}

// 倒计时函数
function startCountdown(seconds) {
  remainingTime.value = seconds;
  const interval = setInterval(() => {
    remainingTime.value -= 1;
    if (remainingTime.value <= 0) {
      clearInterval(interval);
      isThrottled.value = false;
    }
  }, 1000);
}

// 发送验证码
function getEmailCode(){
  throttle(async () => {
    try {
      const formData = new FormData();
      formData.append('to', userStore.getUserInfo.email);
      await getEmailCodeApi(formData);
      ElMessage.success(t('message.GetCodeSuccess'));
      startCountdown(60);
    } catch(error) {
      console.log('getEmailCodeApi - error', error);
    }
  });
};

// 编辑当前行用户方法
const userEdit = (scope, v) => {
  dialogVisible.value = true
  dialogTitle.value = v
}
// 冻结当前用户方法
const userFreeze = (scope, v) => {
  dialogVisible.value = true
  dialogTitle.value = v
}

// 修改用户状态 handleCloseUserStatus 方法
async function handleCloseUserStatus() {
  freezeDialog.value = false
  userStatus.value = ''
}

// 修改用户状态 handleConfirmUserStatus 方法 方法
async function handleConfirmUserStatus() {
  try {
    const { code, data, msg } = await changeStatus({
      userId: unref(userId),
      status: unref(userStatus)
    })
    if (code === 200) {
      ElMessage.success(t('message.EditSuccess'))
    } else {
      ElMessage.error(msg)
    }
  } catch (e) {
    console.log(e)
  } finally {
    getList()
    userStatus.value = ''
    freezeDialog.value = false
  }
}

const rules = reactive({
  userId: [
    { required: true, message: t("message.UserNameIsNull"), trigger: "blur" },
  ],
  userName: [
    { required: true, message: t("message.UserNameIsNull"), trigger: "blur" },
  ],
  password: [
    { required: true, message: t('message.PleaseInputPWD'), trigger: 'blur' },
    { min: 8, max: 16, message: t('message.PWDLength'), trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,16}$/,
      message: t('message.PWDAa09'), trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: t('message.EmailIsNull'), trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: t('message.PleaseInputRightEmail'),
      trigger: 'blur'
    }
  ],
  code: [
    { required: true, message: t('message.CodeIsNull'), trigger: 'blur' },
  ]
})


const userId = ref('')
const rowUserName = ref('')
// 改变用户状态开关 方法
const handleSwitchChange = (val, scope) => {
  userId.value = scope.row.id
  userStatus.value = scope.row.status
  rowUserName.value = scope.row.username
  // userStatus.value = val
  freezeDialog.value = true
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  dialogTitle.value = '';
  dialogTitleText.value = ''
  resetForm()
}

// 关闭冻结dialog
const handleCloseFreeze = () => {
  freezeDialog.value = false
  userStatus.value = ''
  userId.value = ''
  getList()
}


// 重置dialog表单数据
const resetForm = () => {
  ruleForm.userName = ''
  ruleForm.userId = ''
  ruleForm.status = ''
  ruleForm.password = ''
  ruleForm.email = ''
  ruleForm.code = ''
  ruleForm.maturityTime = ''
  ruleForm.remark = ''
  eye.value = true
}

// 重置查询数据方法
const onReset = () => {
  onClear();
  getList();
}

// 清除  queryParams
const onClear = () => {
  queryParams.id = ''
  queryParams.username = ''
  queryParams.email = ''
  queryParams.maturityTime = ''
  queryParams.status = ''
}

// // 搜索方法
// const onSubmit = (username, status) => {
//   // 查询时把 pageIndex 重置为1
//   pageIndex.value = 1
//   getList(username, status);
// }

// 分页
function handleSizeChange(val) {
  pageSize.value = val
  getList()
}

// 分页
function handleCurrentChange(val) {
  pageIndex.value = val
  // getList(queryParams.id, queryParams.username, queryParams.email, queryParams.maturityTime, queryParams.status)
  getList();
}

// 隐藏密码方法
const eye = ref(true)
const inpType = ref('password');
const checkPass = () => {

  localStorage.setItem('eye', eye.value)
  eye.value = localStorage.getItem('eye')
  eye.value = !eye.value;
  inpType.value = inpType.value === 'password' ? 'text' : 'password';
}

// 用户状态列表
const userStatusList = reactive([
  { value: 0, label: t('user.UserFreeze') },
  { value: 1, label: t('user.UserStatus1') },
])
</script>

<style lang="less" scoped>
.query-form {
  text-align: left;
}
</style>